package org.ewicom.ppsaddressbook;

import java.util.List;

import org.ewicom.ppsaddressbook.model.Unit;
import org.ewicom.ppsaddressbook.model.UnitDataSource;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class UnitsList extends ListActivity {

	private static final String TAG = "UnitsList";

	private UnitDataSource unitDataSource;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		unitDataSource = new UnitDataSource(this);
		unitDataSource.open();
	
		List<Unit> units = unitDataSource.getAllUnits();
		
		UnitListAdapter adapter = new UnitListAdapter(this, units);
		setListAdapter(adapter);
		
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Intent intent = new Intent();
		intent.setClass(this, UnitDetails.class);
		intent.putExtra("unit_id", id);
		startActivity(intent);
	}

	@Override
	protected void onResume() {
		unitDataSource.open();
		super.onResume();
	}

	@Override
	protected void onPause() {
		unitDataSource.close();
		super.onPause();
	}
	
	private class UnitListAdapter extends BaseAdapter{

		private List<Unit> units;
		private Context mContext;
		private LayoutInflater inflator;
		
		public UnitListAdapter(Context context, List<Unit> units){
			this.units = units;
			this.mContext = context;
			this.inflator = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
		}
		
		@Override
		public int getCount() {
			return units.size();
		}

		@Override
		public Object getItem(int position) {
			return units.get(position);
		}

		@Override
		public long getItemId(int position) {
			return units.get(position).getId();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final MainListHolder mHolder;
			View v = convertView;
			if(convertView == null){
				mHolder = new MainListHolder();
				v = inflator.inflate(R.layout.unitslist_item, null);
				mHolder.shortUnitName = (TextView) v.findViewById(R.id.shortUnitName);
				mHolder.longUnitName = (TextView) v.findViewById(R.id.longUnitName);
				v.setTag(mHolder);
			}else{
				mHolder = (MainListHolder) v.getTag();
			}
			
			mHolder.shortUnitName.setText(units.get(position).getShortName());
			String longName = units.get(position).getPostcode() + " " + units.get(position).getCity();
			mHolder.longUnitName.setText(longName);
			
			return v;
		}
		
		private class MainListHolder{
			private TextView shortUnitName;
			private TextView longUnitName;
		}
		
	}
}
